//获取头部相关元素
let goBackBtn = document.querySelector("header img");
let headImgEl = document.querySelector("main .header img");
let headShowEl = document.querySelector("main .header div");
let photoEl = document.querySelector(".photo");
let randomEl = document.querySelector(".random");
let logoff = document.querySelector("header span");
let registerTimeEl = document.querySelector(".information .registertime");
let emailEl = document.querySelector(".accountnumber .email");
let passwordEl = document.querySelector(".update-password");
let logoutEl = document.querySelector(".logout");
//获取昵称相关元素
let nicknameBoxEl = document.querySelector(".nickname_box");
let nicknameEl = document.querySelector(".nickname");
let changeNicknameBoxEl = document.querySelector(".changenickname_box input");

let backgroundEl = document.querySelector(".background");
let changeNicknameEl = document.querySelector(".changenickname");
let confirmEl = document.querySelector(".confirm");

if (!localStorage.getItem("token")) {
  window.location.href = "/";
}

goBackBtn.addEventListener("click", function () {
  window.location.href = "./userMmt.html";
});
//切换修改头像页面
headImgEl.addEventListener("click", showHead);

//切换修改昵称页面
nicknameBoxEl.addEventListener("click", changeNickname);

//确定修改昵称
confirmEl.addEventListener("click", confirmBut);

//修改头像
photoEl.addEventListener("change", changeHead);

//获取随机头像
randomEl.addEventListener("click", randomHead);

logoff.addEventListener("click", logoffUser);
function logoffUser() {
  window.location.href = "../public/logoff.html";
}

//获取随机头像
async function randomHead() {
  let res = await axios({
    method: "get",
    url: "http://121.37.252.168:8080/api/user/getDefaultAvatarList"
  });
  console.log(res);

  let num = Math.floor(Math.random() * (8 - 0));
  let headList = res.data.data.avatarList[num];
  let headImg = headList;
  console.log(headImg);

  headImgEl.src = `http://121.37.252.168:8080/api/user/getAvatar/${headList}`;

  let res1 = await axios({
    method: "post",
    url: "http://121.37.252.168:8080/api/user/updateDefaultAvatar",
    headers: {
      Authorization: `Bearer ${localStorage.getItem("token")}`
    },
    data: {
      avatar: headImg
    }
  });
  console.log("res1", res1);
}

//从相册选择上传头像
async function changeHead() {
  if (photoEl.files <= 0) return;
  const file = photoEl.files[0];

  let data = new FormData();
  data.append("avatar", file);

  let res = await axios({
    method: "post",
    url: "http://121.37.252.168:8080/api/user/uploadAvatar",
    headers: {
      Authorization: `Bearer ${localStorage.getItem("token")}`
    },
    data: data
  });
}

//确定修改昵称
async function confirmBut() {
  backgroundEl.classList.toggle("showbackground");
  changeNicknameEl.classList.toggle("showchangenickname");

  let nickname = /^[\w\u4E00-\u9FA5]{4,20}$/;

  if (nickname.test(changeNicknameBoxEl.value) == false) {
    alert("失败");
  } else {
    nicknameEl.value = changeNicknameBoxEl.value;

    let res = await axios({
      method: "post",
      url: "http://121.37.252.168:8080/api/user/updateUsername",
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`
      },
      data: {
        username: changeNicknameBoxEl.value
      }
    });
  }
}

//弹出修改昵称页面
function changeNickname() {
  backgroundEl.classList.toggle("showbackground");
  changeNicknameEl.classList.toggle("showchangenickname");
}

//切换头像动画函数
function showHead() {
  headShowEl.classList.toggle("headshow");
  headShowEl.classList.toggle("headdown");
}

//获取用户头像数据和用户名
async function headImg() {
  let res = await axios({
    method: "post",
    url: "http://121.37.252.168:8080/api/user/getUserInfo",
    headers: {
      Authorization: `Bearer ${localStorage.getItem("token")}`
    }
  });
  headImgEl.src = `http://121.37.252.168:8080/api/user/getAvatar/${res.data.data.avatar}`;

  nicknameEl.value = res.data.data.username;
  changeNicknameBoxEl.value = nicknameEl.value;
  registerTimeEl.textContent = format(res.data.data.created_time);
}
headImg();

async function getEmail() {
  let res = await axios({
    method: "post",
    url: "http://121.37.252.168:8080/api/user/getMailbox",
    headers: {
      Authorization: `Bearer ${localStorage.getItem("token")}`
    }
  });
  emailEl.textContent = res.data.data.email;
}
getEmail();

//转化年月函数
function format(timeStamp) {
  timeStamp = parseInt(timeStamp);
  const time = new Date(timeStamp);
  const year = time.getFullYear();
  let month = time.getMonth() + 1;
  let day = time.getDate();

  month = month < 10 ? "0" + month : month;

  return `${year}-${month}-${day}`;
}

// 修改密码
passwordEl.addEventListener("click", function (e) {
  window.location.href = "./repassword.html";
});

// 登出账号
logoutEl.addEventListener("click", function (e) {
  localStorage.removeItem("token");
  localStorage.removeItem("userinfo");
  window.location.href = "./indextry.html";
});
